<?php
class LtCache
{
	private $ch;

	public function __construct()
	{
		$config = LtObjectUtil::singleton("LtConfig")->get('cache');
		
		$this->ch = new LtStoreFile;
		$this->ch->cacheFileRoot = $config['dir'];
		$this->ch->prefix = 'Ltcache-file-';
		$this->ch->init();
	}
	
	public function add($key, $value, $ttl = 0, $tableName='phps')
	{
		return $this->ch->add($this->getRealKey($tableName, $key), $this->valueToString($value), $ttl);
	}
	
	public function del($key, $tableName='phps')
	{
		return $this->ch->del($this->getRealKey($tableName, $key));
	}
	
	public function get($key, $tableName='phps')
	{
		return $this->stringToValue($this->ch->get($this->getRealKey($tableName, $key)));
	}
	
	public function update($key, $value, $ttl = 0, $tableName='phps')
	{
		if($this->get($key,$tableName)===false)
		{
			return $this->add($key, $value, $ttl, $tableName);
		}
		else
		{
			return $this->ch->update($this->getRealKey($tableName, $key), $this->valueToString($value), $ttl);
		}
	}
	
	protected function getRealKey($tableName, $key)
	{
		return $tableName . "-" . $key;
	}
	
	protected function valueToString($value)
	{
		if (is_object($value) || is_resource($value))
		{
			$str = "return unserialize(\"" . addslashes(serialize($value)) . "\");";
		}
		else
		{
			$str = "return " . var_export($value, true) . ";";
		}
		return $str;
	}
	
	protected function stringToValue($str)
	{
		return eval("$str");
	}
}